package PartD;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.Socket;
import java.util.concurrent.Semaphore;

public class Request implements Runnable {
	
	Socket socket;
	Semaphore sem;
	
	public Request (Socket socket, Semaphore sem) {
		this.socket = socket;
		this.sem = sem;
	}

	@Override
	public void run() {
		try {
			processRequest();
		} catch (Exception e) {
			System.out.println(e);
		}
	}
	
	private void processRequest() throws Exception {

		byte[] buffer = new byte[1024];
		int bytes = 0;
		
		InputStream is = socket.getInputStream();
		DataInputStream dis = new DataInputStream(is);
		DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
		
		while ((bytes = dis.read(buffer)) != -1) {
		    dos.write(buffer, 0, bytes);
		}
		
		is.close();
		dis.close();
		dos.close();
		
		// close the socket and give the permit back
		socket.close();
		sem.release();
	}
}
